#!/usr/bin/perl -w

use strict;
use warnings;

use EBox;
use EBox::Backup;
use EBox::Global;
use EBox::Gettext;
use EBox::ProgressIndicator;

use TryCatch;

use Getopt::Long;

EBox::init();

# process cli
my $progressId = undef;

my $configBackup = 0;
my $bugReport    = 0;
my $fallbackToRO = 0;

my $description = undef;
my $destination = undef;

my $help = 0;


my $optionsOk = GetOptions(
                           'progress-id:i'   => \$progressId,
                           'config-backup'   => \$configBackup,
                           'bug-report|configuration-report'
                                        => \$bugReport,
                           'description=s'   => \$description,
                           'destination=s'   => \$destination,
                           'fallback-to-ro'  => \$fallbackToRO,
                           'help'            => \$help,
                          );

if (not $optionsOk) {
  print "Incorrect options\n";
  print "$0 --help for usage instructions\n";
  exit 1;
}

if ($help) {
  usage();
  exit 0;
}

# see if we have incompatible operation modes
my $incompatibleModes = grep { $_  }  ($configBackup,  $bugReport);
if ($incompatibleModes > 1) {
  die "You can only choose one backup mode from --config-backup,   or --bug-report. (--config-restore is the default restore mode)";
}

my %params;

if ($bugReport) {
    my $incompatibleWithBug = grep { $_  }  ($description, $progressId);
    if ($incompatibleWithBug) {
        die "You have specified options incompatibles with the bug report mode)";
    }
}


if ($progressId) {
    my $progress = EBox::ProgressIndicator->retrieve($progressId);
 
    # put  progress indicator param
    $params{progress} = $progress;
}

if (defined $description) {
    $params{description} = $description;
}

if (defined $destination) {
    $params{destination} = $destination;
}

if ($fallbackToRO) {
    $params{fallbackToRO} = 1;
}

my $progress = $params{progress};
try {
    if (not $bugReport) {
        my $file = EBox::Backup->makeBackup(%params);
        print "Backup stored into file $file\n";
    } else {
        # with bug report we ignore all other options
        my $reportFile = EBox::Backup->makeBugReport();
        print "Bug report stored into file $reportFile\n";
    }
} catch ($e) {
    if ($progress) {
        $progress->setAsFinished(1, $e->text);
    }

    $e->throw();
}

sub usage
{
  print <<END;
  Usage:
  $0  [OPTION\]...
  $0  --help

  Options:
    --config-backup (default backup mode)
    --configuration-report --bug-report

    --description <description>
    --fallback-to-ro
    --progress-id (only needed for web framework)
END
}

1;
